#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
	int pipe_fd[2] = {0};
	if(pipe(pipe_fd) < 0)
	{
		perror("pipe");
		return 1;
	}
	printf("fd[0]:%d fd[1]:%d\n",pipe_fd[0],pipe_fd[1]);
	pid_t id = fork();
	if(id < 0)
	{
		perror("fork");
		return 2;
	}
	else if(id == 0)
	{
		close(pipe_fd[0]);
		const char* msg = "hello bit!";
		int count = 0;
		while(1)
		{
			write(pipe_fd[1],msg,strlen(msg));
			count++;
			printf("write:%d\n",count);
			sleep(1);
		}
		close(pipe_fd[1]);
		exit(0);
	}
	else
	{
		close(pipe_fd[1]);
		char buffer[64];
		while(1)
		{
			buffer[0] = 0;
			ssize_t size = read(pipe_fd[0],buffer,sizeof(buffer)-1);
			if(size > 0)
			{
				buffer[size] = 0;
				printf("parent get message from child: %s\n",buffer);
			}
			else if(size == 0)
			{
				printf("pipe file close, child quit!\n");
				break;
			}
			else
				break;
		}
		int status = 0;
		if(waitpid(id,&status,0) > 0)
			printf("child quit,wait success!,sig: %d\n",status&0X7F);
		close(pipe_fd[0]);
	}
	return 0;
}


